# from .setting import mqtthost
# 为了能在外部脚本中调用Django ORM模型，必须配置脚本环境变量，将脚本注册到Django的环境变量中
import json
import logging
import os
from threading import Thread

import django
from paho.mqtt.client import Client

from ..settings import SERVER_TOPIC, MQTT_HOST
from ..models import DeviceRunningInfo
from datetime import datetime

# 第一个参数固定，第二个参数是工程名称.settings
os.environ.setdefault('DJANGO_SETTING_MODULE', 'lot.settings')
django.setup()


class mqttContoller(Client):
    def __init__(self, host, topic):
        self.host = host
        self.topic = topic
        Client.__init__(self)
        self.on_message = self.receivedmessagemethod

    def connecttohost(self):
        self.connect(self.host)
        self.subscribe(topic=self.topic, qos=2)

    def receivedmessagemethod(self, client, userdata, message):
        # TODO finish the method here
        # gatewayDevice = models.GatewayDevice.objects.filter(gateway_num=message.topic).count()
        # if gatewayDevice < 0:
        #     logging.info('have no gateway')
        #     return
        try:
            msgJson = json.loads(message.payload.decode('utf8'))
        except Exception:
            logging.info('msg invalid')
            return
        deviceRunInfo = DeviceRunningInfo(device=msgJson['deviceid'], device_name=msgJson['devicename'],
                                          device_running_info=msgJson['devicerunninginfo'], time_stamp=datetime.now())
        deviceRunInfo.save()


MQTTClient = mqttContoller(host=MQTT_HOST, topic=SERVER_TOPIC)


def MQTTStart():
    MQTTClient.connecttohost()
    MQTTClient.loop_forever()


def startMQTTThread():
    MQTTthread = Thread(target=MQTTStart)
    MQTTthread.start()


if __name__ == '__main__':
    startMQTTThread()